import Vue from 'vue';
import store from './store';
import App from './App';
import VConsole from 'vconsole';
import md5 from 'js-md5';
import CryptoJS from 'crypto-js'; // 引入crypto-js库
import { jsonp } from 'vue-jsonp';
//import {YdSetUtils}  './static/ydsets/data.js?r=v1.2';
const YDDOM = require('./static/ydsets/data.js'); //TODO 有缓存
//console.log("YdSetUtils",YDDOM.YdSetUtils);

/**
 *  css部分使用了App.vue下的全局样式和iconfont图标，有需要图标库的可以留言。
 *  示例使用了uni.scss下的变量, 除变量外已尽量移除特有语法,可直接替换为其他预处理器使用
 */
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}
//TODO 随机数据
const mathRand = () =>{
	var random = (new Date()).getTime();
	return random;
}



const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}
/**
 * 是否登录,接口判断
 */
const isLoginApi = function(res) {
	let pla = getPlatform();
	//登录失效
	if (res.code == -202) {
		//先清空本地缓存
		uni.removeStorageSync('user');
		uni.removeStorageSync('islogin');
		uni.removeStorageSync('token');
		//跳转到登录授权页面
		uni.navigateTo({ url:"/pages/index/index" });
		return false;
	}
}
//TODO 全局变量值
const getSourceDevice = function (){
	let devOption={
		platform: uni.getStorageSync('ENV_PlatForm')?uni.getStorageSync('ENV_PlatForm'):null,
		isWechat: uni.getStorageSync('ENV_WeChatMobile')?uni.getStorageSync('ENV_WeChatMobile'):false,
	}
	return devOption;
}


//TODO 全局[动态]加密
const sysEncryptAES = function (data,secretKey,ivChar){
	let encryData = data;
	if(null!== data && typeof(data)==='object'){
		encryData = JSON.stringify(data);
	}
	let secEnc = CryptoJS.enc.Utf8.parse(secretKey);
	let secOption = {
		mode:CryptoJS.mode.ECB, //TODO 默认为AES-ECB-128模式:对应PHP后台方案----[AES-128-ECB]
		padding:CryptoJS.pad.Pkcs7
	};
	//TODO 加密方案上传：iv:ivData,
	let ivData = CryptoJS.enc.Utf8.parse(ivChar);
	if(null !== ivChar && ivChar!==false && ivChar!=="" && undefined !== ivData && false !== ivData){
		secOption.mode = CryptoJS.mode.CBC;
		secOption.iv = ivData;
	}
	//TODO 方案处理，转换为数据型
	let secRes = CryptoJS.AES.encrypt(encryData,secEnc,secOption).toString();
	return secRes;
}


//TODO 全局[动态]解密
const sysDecryptAES = function (data,secretKey,ivChar){
	let encryData = data;
	let secEnc = CryptoJS.enc.Utf8.parse(secretKey);
	let secOption = {
		mode:CryptoJS.mode.ECB, //TODO 默认为AES-ECB-128模式:对应PHP后台方案----[AES-128-ECB]
		padding:CryptoJS.pad.Pkcs7
	};
	//TODO 加密方案上传：iv:ivData,
	let ivData = CryptoJS.enc.Utf8.parse(ivChar);
	if(null !== ivChar && ivChar!==false && ivChar!=="" && undefined !== ivData && false !== ivData){
		secOption.mode = CryptoJS.mode.CBC;
		secOption.iv = ivData;
	}
	//TODO 方案处理，转换为数据型
	try {
		let secRes = CryptoJS.AES.decrypt(encryData,secEnc,secOption);
		console.log("【decrypted】---> 解密钥=" + secretKey,secOption,secRes);
		return secRes.toString(CryptoJS.enc.Utf8);
	} catch (error) {
		console.log("【decrypted】---> 解密失败了" + secretKey,error);
		return false;
	}
}


//TODO 多种解密方法共同处理
const doParseUrlParamData = function (inputData,userToken){
	let privateLen =  16;
	if(!inputData ||!userToken){
		return FALSE ;
	}
	//TODO 第1种；md5方案1
	let privateK1 = md5(userToken).substring(0,privateLen);
	let decData1 = sysDecryptAES(inputData,privateK1,null);
	//console.log("【doParseUrlParamData】==> 执行方案1:"+privateK1,decData1);
	if(undefined !== decData1 && null!==decData1 && false !== decData1 && decData1!==''){
		return decData1;
	}
	
	//TODO 第2种；md5方案2
	let newToken2 = "KILLTOKEN" + userToken;
	let privateK2 = md5(newToken2).substring(0,privateLen);
	let decData2 = sysDecryptAES(inputData,privateK2,null);
	//console.log("【doParseUrlParamData】==> 执行方案2:"+privateK2,decData2);
	if(undefined !== decData2 && null!==decData2 && false !== decData2 && decData2!==''){
		return decData2;
	}
	
	//TODO 第3种；md5方案3
	let newToken3 = "YDLM_"+md5("YDLMUSER")+userToken.substring(0,10);
	let privateK3 = md5(newToken3).substring(0,privateLen);
	let decData3 = sysDecryptAES(inputData,privateK3,null);
	//console.log("【doParseUrlParamData】==> 执行方案3:"+privateK3,decData3);
	if(undefined !== decData3 && null!==decData3 && false !== decData3 && decData3!==''){
		return decData3;
	}
	
	//TODO 第4种；Token直连
	let privateK4 = userToken.substring(0,privateLen);
	let decData4 = sysDecryptAES(inputData,privateK4,null);
	//console.log("【doParseUrlParamData】==> 执行方案4:"+privateK4,decData4);
	if(undefined !== decData4 && null!==decData4 && false !== decData4 && decData4!==''){
		return decData4;
	}
	return false ;
}

/*获取平台类型 */
const getPlatform = function() {
	let platform = uni.getStorageSync('platform');
	// #ifdef MP-WEIXIN
	platform = 'wechatMiniApp'; //微信小程序
	// #endif

	//若是微信公众号后
	if (isWechat()) {
		platform = 'wechatMP';
	}

	// #ifdef H5
	if (!platform) {
		platform = 'h5'; //H5
	}
	// #endif

	// #ifdef APP-PLUS
	if (uni.getSystemInfoSync().platform == 'ios') {
		platform = 'ios';
	} else {
		platform = 'android';
	}
	// #endif 
	return platform;
}

const isWeChatPC = function() {
	var userAgent = navigator.userAgent.toLowerCase();
	return userAgent.indexOf('windows') !== -1 || userAgent.indexOf('mac') !== -1;
}

const isWeChatMobile = function() {
	var userAgent = navigator.userAgent.toLowerCase();
	return userAgent.indexOf('android') !== -1 || userAgent.indexOf('iphone') !== -1 || userAgent.indexOf('ipad') !== -1;
}


/*是否微信浏览器*/
const isWechat = function() {
	// #ifndef H5
	return false;
	// #endif

	// #ifdef H5
	let ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
	// #endif
};

/**
 * 获取当前路由
 */
const routelinks = function() {
	//当前页面路由地址
	let routes = getCurrentPages();
	let curRoute = routes[routes.length - 1].route //获取当前页面路由
	let curParam = routes[routes.length - 1].options; //获取路由参数
	let cparam = ''
	for (let key in curParam) {
		cparam += '&' + key + '=' + curParam[key]
	}
	cparam = cparam.replace('&', '');
	let routestr = curRoute + '?' + cparam;
	//不等于登录，其他都作为登录后默认返回路径
	let curRouteNot = ['pages/index/index']
	if (curRouteNot.indexOf(curRoute) < 0 && routestr != '' && routestr != null && routestr != NaN) {
		uni.setStorageSync('preRoute', routestr);
	} 
	//TODO 不提交完整链接
	if(curRoute=="pages/article/index"){
		routestr="pages/article/index?r=1";
	}
	return routestr.replace(/^(\s|\/)+|(\s|\/)+$/g, '');
};
/**
 * 显示微信打开工具
 */
const WchatShowLayer = function (){
	// 创建一个新的div元素
	var div = document.createElement('div');
	// 设置div的内容
	div.innerHTML = '<h2 style="text-align:center;padding-top:88px">请使用手机微信打开页面</h2>';
	// 将div插入到body中
	document.body.appendChild(div);
	return ;
}

/**
 * 万能跳转，根据不同类型做跳转
 */
const isSwitchTab = function(routestr) {
	//tab导航页面
	let curSwitchTab = ['pages/index/index', 'pages/cate/cate', 'pages/cart/cart', 'pages/user/user'];
	let routeArr = routestr.split('?');
	console.log(routeArr);
	console.log(curSwitchTab.indexOf(routeArr[0]));
	if (curSwitchTab.indexOf(routeArr[0]) >= 0) {
		console.log('r1');
		return 1;
	}
	console.log('r0');
	return 0;
}


/**
 * 网络请求
 * @param {Object} req
 */
const request = function(req) {
	let sysVersion  = getApp().globalData.version;
	let accessToken = uni.getStorageSync("token");
	let readVersion = uni.getStorageSync("ENV_ReaderVersion");//TODO 本地存储的阅读版本号
	let platform = getPlatform();
	let routestr = routelinks(); 
	let domain = location.href.split('/wxread/')[0];
	//TODO 请求参数 'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
	let requestParam = {"version":sysVersion,"platform":platform};
	
	//TODO 其它参数【参数处理】
	requestParam.domain = domain ? domain : "";
	requestParam.token =  accessToken ? accessToken:"";
	requestParam.readVersion = readVersion ? readVersion : "";
	requestParam.routelinks = routestr ? routestr : "";
	//TODO 发起接口请求
	if (null !== req.data && undefined !== req.data && false !== req.data) {
		requestParam = Object.assign(requestParam, req.data);
	}
	//TODO 请求接口操作
	jsonp(req.url, requestParam,30000)
		.then(res => {
			req.success(res); 
		})
		.catch(error => {
			req.complete(error);
		});
}

//验证手机
const check_mobile = function(mobile) {
	if (!(/^1[3456789]\d{9}$/.test(mobile))) {
		return 0;
	}
	return 1;
}

Vue.config.productionTip = false;
Vue.prototype.$fire = new Vue();
Vue.prototype.$store = store;
Vue.prototype.$ydsetdata = YDDOM.YdSetUtils;
 
//5.四舍五入保留2位小数（不够位数，则用0替补
Vue.prototype.fnum = function(x) {
	var f = parseFloat(x);
	if (isNaN(f)) {
		return 0;
	}
	f = Math.round(x * 100) / 100;
	return f;
}
 
//跳转链接,jpath:链接,jtype:类型1一般链接|2有返回链接|3导航链接
Vue.prototype.navurl = function(jpath, jtype) {
	if (jtype == 1) {
		uni.redirectTo({
			url: jpath
		});
	} else if (jtype == 2) {
		uni.navigateTo({
			url: jpath
		});
	} else if (jtype == 3) {
		uni.redirectTo({
			url: jpath
		});
	}
	else if(jtype == -1){
		// 返回上一页
		  uni.navigateBack({
			delta: 1 // 默认值是1，表示返回的页面层数
		  });
	}
}


//处理图片
Vue.prototype.dimg=function(img){
	if(img==''||img==null||img==[]){
		return img;
	}
	var dtype = typeof img;
	let img_list_r;
	//若单个图片
	if(dtype=='string'){ 
		img_list_r = img;
		if(img.indexOf("http") != 0){
			img_list_r = getApp().globalData.furl+img;
		}
	}else{
		img_list_r = [];
		for (let i=0; i<img.length; i++){
			let tv = img[i];
			if(tv.indexOf("http") != 0){
				tv = getApp().globalData.furl+tv;
			}
			img_list_r[i] = tv;
		}
	}
	return img_list_r;
}

//格式化时间戳-yyyy-MM-dd HH:mm:ss格式
Vue.prototype.ftime = function(timestamp) {
 let date = new Date(timestamp*1000);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;
} 

Vue.prototype.ftimeny = function(timestamp) {
 let date = new Date(timestamp*1000); 
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  // return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${month}.${day} ${hours}:${minutes}:${seconds}`;
} 

//格式化时间戳-yyyy-MM-dd格式
Vue.prototype.fdate = function(timestamp) {
	let date = new Date(timestamp*1000);
	let year = date.getFullYear();
	let month = String(date.getMonth() + 1).padStart(2, '0'); //注意月份是从0开始的，所以需要加1
	let day = String(date.getDate()).padStart(2, '0');
	// return `${year}-${month}-${day}`; //返回 2019-10-31
	return `${year}.${month}.${day}`; 
}

//TODO 全局文章key加密
Vue.prototype.sysParseUserData = function(inputData) {
	let jmToken = uni.getStorageSync('token');
	//let privateKey = jmToken.substring(0,16);//TODO 取最后几位数据数据
	//console.log("【GET-解密】解密内容:" , inputData);
	//TODO 多种解密方法共同处理
	let decData = doParseUrlParamData(inputData,jmToken,null);
	let decJson = decData ? JSON.parse(decData) : false;
	let parseKeyValue = decJson.key || null;
	let parseMdstr = decJson.mdstr || null;
	//console.log("【GET-解密】解密结果数据 Key="+parseKeyValue ,decData);
	if(null !== decData && null !== decJson && false !== decJson &&   null !== parseKeyValue && null !== parseMdstr ){
		//TODO 解析数据内容
		let mdLen = parseMdstr.length;
		let userId = parseKeyValue.substring(0,12);		//TODO 会员ID; 
		let userFbb = parseKeyValue.substring(12,20);	//TODO 会员ID; 
		let usdMethod = parseKeyValue.substring(20,24);	//TODO 会员ID; 
		let uvkey = parseKeyValue.substring(24,44);		//TODO 会员ID; 
		let lastValue = parseKeyValue.substring(44,45);	//TODO 会员ID; 
		let lastUv2 = parseKeyValue.substring(54,64);	//TODO 会员ID;
		let lastUv3 = parseMdstr.substring(mdLen-2,mdLen);//TODO 取最后两位
		let lastMDstr = parseMdstr.substring(0,mdLen-2);//TODO 取前面所有数据
		let fullUvKey = uvkey; 
		//TODO数据验证是否合适
		if(null === uvkey || false === uvkey || uvkey.length!==20 || !lastMDstr){
			return false;
		}
		if(lastUv2 && lastUv2.length==10 ) {
			fullUvKey = fullUvKey + lastUv2;
		}
		if(lastUv3 && lastUv3.length==2){
			fullUvKey = fullUvKey + lastUv3;
		}
		//TODO 数据内容
		let moreData = {
			"userId":Number(userId),
			"userFbb":Number(userFbb),
			"usdMethod":Number(usdMethod),
			"lastKey":Number(lastValue),
			"uvkey":fullUvKey,
		};
		decJson.mdstr = lastMDstr;
		decJson.childOption = moreData; //TODO 解析数据
		return decJson;
	}else{
		return false;
	}
}


//TODO 全局文章key加密
Vue.prototype.sysArticleAddEncryKey = function(targetChar,method,privateKey) {
	let NewMD5Key = null;
	let systemPrikey=null;
	let jmToken = uni.getStorageSync('token');
	if(!method || null === method || method==0){
		return false;
	}
	if(null === jmToken || jmToken===""){
		return false;
	}
	//TODO 第1层方案【base64】
	let myChar = atob("dXNlZHRva2Vu"); 
	if(method==1){
		let firstToken = jmToken.substring(0,10); 			//TODO 取前10位
		NewMD5Key = btoa(firstToken+":"+targetChar + myChar);	//TODO base64位加密
		//console.log("【新系统加密-1】使用Token："+ jmToken, NewMD5Key);
		return NewMD5Key;
	}
	//TODO 第2层方案【加密】
	if(method==2){
		systemPrikey = this.$md5(jmToken).substring(0,16);
		NewMD5Key = sysEncryptAES(targetChar,systemPrikey,null);	//TODO 首层加密
		//console.log("【新系统加密-2】使用Private："+ systemPrikey, NewMD5Key);
		return NewMD5Key;
	}
	
	//TODO 第2层方案【加密】
	if(method==3) {
		systemPrikey = this.$md5(privateKey).substring(0,16);
		NewMD5Key = sysEncryptAES(targetChar,systemPrikey,null);
		//console.log("【新系统加密-3】使用Private："+ systemPrikey, NewMD5Key);
		return NewMD5Key;
	}
	return false; 
}

//判断是否微信浏览器  wechatMP h5
// if(getPlatform()!='h5'){
// if(getPlatform()!='wechatMP'){
	
// 	// 创建一个新的div元素
// 	var div = document.createElement('div');
// 	// 设置div的内容
// 	div.innerHTML = '<h2 style="text-align:center;padding-top:88px">请使用手机微信打开页面</h2>';
// 	// 将div插入到body中
// 	document.body.appendChild(div);
// 	// throw new Error('请使用微信浏览器打开');
// 	throw SyntaxError('请使用手机微信浏览器打开');
// }

//TODO 配置本地环境内容[平台和手机环境,微信平台：ENV_PlatForm=wechatMP和手机端：ENV_WeChatMobile=true]
let currentPlatForm = getPlatform();
let isWechatMobile 	=  isWeChatMobile();
//TODO 测试模式配置来源
let isWechatBrowron = isWechat();
console.log("[初始当前环境]平台类型和是否微信内置浏览器",currentPlatForm,isWechatMobile,isWechatBrowron);
uni.setStorageSync('ENV_PlatForm', currentPlatForm);
uni.setStorageSync('ENV_WeChatMobile', isWechatMobile);
uni.setStorageSync('ENV_WeChatBrowron', isWechatBrowron);
//TODO 微信平台只能用手机浏览器打开
if(currentPlatForm=="wechatMP"){
	//TODO 禁止分享 
	document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
	    WeixinJSBridge.call('hideOptionMenu');
	});
	if(isWechatMobile !== true){
		WchatShowLayer();
		console.log("请使用手机微信浏览器打开=====跳过请求拦截");
		throw SyntaxError('请使用手机微信浏览器打开');
	}
}

//TODO 主入口
Vue.prototype.$api = {
	msg,
	prePage,
	request,
	isLoginApi,
	getSourceDevice,
	routelinks,
	isSwitchTab,
	isWechat,
	check_mobile,
	sysEncryptAES,
	sysDecryptAES
};
Vue.prototype.$md5 = md5;
Vue.prototype.$console = function(...args){
	console.log(args);
};
App.mpType = 'app';
const app = new Vue({ ...App });
app.$mount();

//TPDO 初始数据【来源平台】
const pageGlobalData = getApp().globalData;
console.log("[pageGlobalData] 配置数据=>",pageGlobalData);
if(pageGlobalData.platformName!==null && pageGlobalData.platformName!==false && pageGlobalData.platformName!==""){
	uni.setStorageSync('ENV_PlatForm', pageGlobalData.platformName);
}
if(pageGlobalData.isWechat!==null){
	uni.setStorageSync('ENV_WeChatMobile', pageGlobalData.isWechat);
}
//TPDO 初始数据【阅读版本-version】
if(pageGlobalData.readerVersion!==null && pageGlobalData.readerVersion!==false && pageGlobalData.readerVersion!==""){
	uni.setStorageSync('ENV_ReaderVersion', pageGlobalData.readerVersion);
}else{
	uni.setStorageSync('ENV_ReaderVersion', undefined);
}
//TOOD 启动模拟器 [初始化控制台] 
//new VConsole();